import { Form } from "../model/base/form";
import { List } from "../model/base/list";
import { ListSearch } from "../model/base/list_search";
import { h, type VNode } from "vue";
import { pagebuttonStore } from "../store";
import type { RuleItem } from "async-validator";
import type { listButton } from "@b/model/base/type";

export class UserListSearch extends ListSearch<interfaceUserSearch> {
    constructor() {
        super()
        this.data.name = ""
        this.reactiveProp = ['roleId', 'departmentId']
    }
    setLabels(roles: any[], departments: any[]) {
        this.setItem({
            name: {
                prop: "name",
                label: "姓名",
                type: "text",
                clearable: true,
                show: ({ isPhone }) => !isPhone
            },
            roleId: {
                prop: "roleId",
                label: "身份",
                link: true,
                clearable: true,
                type: 'select',
                options: roles
            },
            departmentId: {
                prop: "departmentId",
                label: "部门",
                link: true,
                type: 'cascader',
                clearable: true,
                props: {
                    label: 'name',
                    value: 'id',
                    children: 'departments',
                },
                options: departments
            },
        }, this.labels)
    }
    async getRoles() {
        return (await this.request('/role/select', { method: 'GET', cache: 'global' })).map((item: any) => ({ label: item.name, value: item.id || 0 }))
    }
    async getDepartments() {
        return (await this.request('/department/tree', { method: 'GET', cache: 'global' }))
    }
    async init() {
        const roles = await this.getRoles()
        const departments = await this.getDepartments()
        this.setLabels(roles, departments)
    }
}
export class Userlist extends List<interfaceUser> {
    constructor() {
        super()
        this.baseUrl = '/user'
        this.title = "用户列表"
        this.select = undefined
        this.setItem({
            id: { prop: "id", label: "ID", type: 'text', width: 80 },
            name: { prop: "name", label: "姓名", type: 'text', width: 120 },
            headImg: {
                prop: "headImg", label: "头像", type: 'image', size: 80, width: 120
            },
            username: { prop: "username", label: "账号", type: 'text', width: 120 },
            phone: { prop: "phone", label: "手机号", type: 'text', width: 120 },
            department: { prop: "department.name", label: "部门", type: 'text', width: 120 },
            roles: { prop: "roles", label: "身份", type: 'customize', formatter: ({ value }) => value?.map((i: interfaceRole) => i.name).join(',') || '' },
            createTime: { prop: "createTime", type: 'text', label: "创建时间", overflow: true }
        }, this.labels)
        this.editButton = () => {
            const but = pagebuttonStore().button
            const buttons: VNode[] = []
            if (but.has('base:user:add')) {
                buttons.push(h('div', { className: 'textbutton', onClick: this.add }, but.get('base:user:add')))
            }
            return buttons
        }
        this.actions = () => {
            const but = pagebuttonStore().button;
            const actions: listButton<interfaceUser>[] = []
            if (but.has('base:user:delete')) {
                actions.push({
                    text: but.get('base:user:delete') || '', hasConfirm: true,
                    confirmText: '是否删除当前用户',
                    type: 'danger', onClick: (data, index) => {
                        this.deleteItem(index)
                    }
                })
            }
            if (but.has("base:user:update")) {
                actions.push({
                    text: but.get("base:user:update") || '',
                    type: 'primary',
                    onClick: (data) => {
                        this.edit(data.id)
                    }
                })
            }
            if (but.has('base:user:reset_password')) {
                actions.push({
                    text: but.get('base:user:reset_password') || '', confirmText: '是否重置当前账户密码',
                    type: 'warning', hasConfirm: true, onClick: (data) => {
                        if (data.id) {
                            this.resetPassword(data.id)
                        }
                    }
                })
            }
            actions.push({
                text: '会话', onClick: (data) => {
                    this.createC2C(data.id)
                }
            })
            return actions
        }
    }
    routertoC2C(_C2CId: number) {
        console.log(_C2CId)
        throw new Error('C2C跳转未设置')
    }
    async createC2C(UserId?: number) {
        const res = await this.request('/vv/group/createC2C', { parames: { id: UserId } })
        if (res) {
            this.routertoC2C(res)
        }
    }
    async resetPassword(id: number) {
        return await this.request('/user/reset_password', { parames: { id } })
    }
    onRouterToInfo(_id?: number) {
        console.log(_id)
        throw new Error('未设置跳转函数')
    }
    async edit(_id?: number) {
        console.log(_id)
        throw new Error('未设置编辑函数')
    }
    async add(_id?: number) {
        console.log(_id)
        throw new Error('未设置新增函数')
    }
}

export class UserForm extends Form<interfaceUser> {
    constructor() {
        super()
        this.baseUrl = '/user'
        this.data.status = 1
        this.upload = ["headImg"]
        this.title = "用户详情"

    }
    setLabels(role: any, department: any) {
        const vName: RuleItem[] = [{
            type: 'string', required: true, validator: (rule, value) => value ? value.length < 16 && value.length >= 2 : false,
            message: '昵称长度在2-16之间'
        }]
        const vPhone: RuleItem[] = [{
            type: 'string', required: true, validator: (rule, value) => value ? value.length < 16 && value.length >= 4 : false,
            message: '账号长度为4-16'
        }]
        const vRoles: RuleItem[] = [{ type: 'string', validator: (rule, value) => value ? value.length !== 0 : false, message: '身份必选' }]

        this.rule = {
            name: vName,
            username: vPhone,
            roleIds: vRoles
        }
        this.setItem({
            name: {
                prop: 'name',
                label: '姓名',
                type: 'text',
                required: true,
                rule: Form.getVantRule(vName)
            },
            username: {
                prop: 'username',
                label: '账号',
                type: 'text',
                rule: Form.getVantRule(vPhone),
                required: true,
                default: '无'
            },
            department: {
                prop: 'department.id',
                label: '科室',
                type: 'select',
                props: {
                    label: "name",
                    value: "id"
                },
                options: department,
                selectName: 'name',
                required: true,
            },
            roleIds: {
                prop: 'roleIds',
                label: '身份',
                type: 'select',
                props: {
                    label: "label",
                    value: "id"
                },
                options: role,
                selectName: 'roleName',
                multiple: true,
                required: true,
                rule: Form.getVantRule(vRoles),
                overflow: true,
                link: true
            },
            headImg: {
                prop: 'headImg',
                label: '头像',
                type: 'image',
                size: 60,
                after: (url: string) => {
                    this.showCroppe(url)
                    return url
                },
            }
        }, this.labels)
    }
    async getRole() {
        return (await this.request('/role/select', { method: 'GET', cache: 'global' })).map((item: any) => ({ label: item.name, value: item.id || 0 }))
    }
    async getDepartment() {
        return (await this.request('/department/select/child', { method: 'GET', cache: 'global' })).map((item: any) => ({ label: item.name, value: item.id || 0 }))
    }
    showCroppe(url: string) {
        throw new Error(url + '未设置显示编辑图片的方法')
    }
    async init() {
        const role = await this.getRole()
        const department = await this.getDepartment()
        this.setLabels(role, department)
    }
}
